package com.itqdkj.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itqdkj.health.constant.MessageConstant;
import com.itqdkj.health.constant.RedisConstant;
import com.itqdkj.health.entity.PageResult;
import com.itqdkj.health.entity.QueryPageBean;
import com.itqdkj.health.entity.Result;
import com.itqdkj.health.pojo.Setmeal;
import com.itqdkj.health.service.SetmealService;
import com.itqdkj.health.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Reference
    SetmealService setmealService;
    @Autowired
    JedisPool jedisPool;
    /**
     * 新增套餐
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        try {
            setmealService.add(setmeal,checkgroupIds);
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
    }
    @RequestMapping(value = "/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return setmealService.pageQuery(queryPageBean);
    }
    //上传本地图片到七牛云
    @RequestMapping(value = "/upload")
    public Result upload(@RequestParam(value = "imgFile")MultipartFile imgFile){
        try {
            //获取文件名
            String fileName = imgFile.getOriginalFilename();
            //获取文件后缀（.jpg/.png）
            String ext = fileName.substring(fileName.lastIndexOf("."));
            //随机生成（UUID）为了防止文件名冲突，统一随机生成uuid重命名文件名
            fileName = UUID.randomUUID().toString()+ext;
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //在上传到七牛云的同时将图片的名称，存放到redis中的集合（名称为：setmealPicResources）
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
        }
    }
}
